package db.swing1;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;

import javax.swing.table.AbstractTableModel;

/**
 * Beispielklasse, die ein Tabellenmodell auf Basis eines ResultSets definiert.
 * <br>
 * <b>Auflage 2</b>
 * 
 * @author Michael Inden
 * 
 * Copyright 2012 by Michael Inden 
 */
public final class ResultSetTableModel extends AbstractTableModel {
	private final ResultSet resultSet;

	private final ResultSetMetaData resultSetMetaData;

	ResultSetTableModel(final ResultSet resultSet) throws SQLException {
		this.resultSet = resultSet;
		this.resultSetMetaData = resultSet.getMetaData();
	}

	@Override
	public int getRowCount() {
		try {
			final int currentRow = resultSet.getRow();
			resultSet.last();
			final int lastRow = resultSet.getRow();
			resultSet.absolute(currentRow);
			return lastRow;

		} catch (final SQLException sqlException) {
			return 0;
		}
	}

	@Override
	public int getColumnCount() {
		try {
			return resultSetMetaData.getColumnCount();
		} catch (final SQLException sqlException) {
			return 0;
		}
	}

	@Override
	public String getColumnName(int columnIndex) {
		try {
			// => ber�cksichtigt auch Aliase im Gegensatz zu getColumnName
			return resultSetMetaData.getColumnLabel(columnIndex + 1);
		} catch (final SQLException sqlException) {
			return super.getColumnName(columnIndex);
		}
	}

	@Override
	public Class<?> getColumnClass(int columnIndex) {
		try {
			return Class.forName(resultSetMetaData
					.getColumnClassName(columnIndex + 1));
		} catch (final SQLException | ClassNotFoundException exception) {
			return Object.class;
		}
	}

	@Override
	public Object getValueAt(int rowIndex, int columnIndex) {
		try {
			resultSet.absolute(rowIndex + 1);
			return resultSet.getObject(columnIndex + 1);
		} catch (final SQLException sqlException) {
			return null;
		}
	}
}